<template>
  <div class="container">
    <Breadcrumb :items="[$t('订单管理'), $t('对账管理')]" />
    <a-card class="general-card">
      <template #title>
        {{ $t('对账批次管理') }}
      </template>
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            label-align="left"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-layout="inline"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="batchNo" :label="$t('批次号')">
                  <a-input v-model="searchForm.batchNo" :placeholder="$t('请输入批次号')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="platformId" :label="$t('平台ID')">
                  <a-input v-model="searchForm.platformId" :placeholder="$t('请输入平台ID')" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="timeRange" :label="$t('对账时间')">
                  <a-range-picker
                    v-model="timeRange"
                    style="width: 100%"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="status" :label="$t('状态')">
                  <a-select v-model="searchForm.status" :placeholder="$t('请选择状态')" style="width: 100%">
                    <a-option value="0">未开始</a-option>
                    <a-option value="1">进行中</a-option>
                    <a-option value="2">已完成</a-option>
                    <a-option value="3">已取消</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="16">
                <a-space>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ $t('搜索') }}
                  </a-button>
                  <a-button @click="reset">
                    <template #icon>
                      <icon-refresh />
                    </template>
                    {{ $t('重置') }}
                  </a-button>
                </a-space>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 32px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="horizontal" size="medium">
            <a-button type="primary" @click="handleImport">
              <template #icon>
                <icon-upload />
              </template>
              {{ $t('导入对账') }}
            </a-button>
            <a-button type="primary" status="success" @click="exportData">
              <template #icon>
                <icon-download />
              </template>
              {{ $t('导出') }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider style="margin-top: 0" />
      <a-table
        row-key="id"
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data="renderData"
        :bordered="false"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #totalCount="{ record }">
          <span>{{ record.totalCount || 0 }}</span>
        </template>
        <template #successCount="{ record }">
          <span style="color: #52C41A">{{ record.successCount || 0 }}</span>
        </template>
        <template #failCount="{ record }">
          <span style="color: #FF4D4F">{{ record.failCount || 0 }}</span>
        </template>
        <template #status="{ record }">
          <a-tag :color="record.status === 0 ? 'blue' : record.status === 1 ? 'green' : ''">
            {{ record.status === 0 ? '处理中' : record.status === 1 ? '处理完成' : '-' }}
          </a-tag>
        </template>
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="viewDetail(record)">
              <template #icon><icon-eye /></template>
              {{ $t('详情') }}
            </a-button>
            <a-button type="text" size="small" @click="viewRecords(record)">
              <template #icon><icon-unordered-list /></template>
              {{ $t('对账记录') }}
            </a-button>
            <a-button type="text" status="danger" size="small" @click="exportBatchRecords(record)">
              <template #icon><icon-download /></template>
              {{ $t('导出记录') }}
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 对账结果对话框 -->
    <ReconciliationResult
      v-model:visible="resultVisible"
      :result-list="reconciliationResult"
      :statistics="reconciliationStatistics"
      @save="handleSaveResult"
    />

    <!-- 上传对话框 -->
    <UploadDialog
      v-model:visible="uploadVisible"
      @success="handleUploadSuccess"
    />

    <!-- 对账批次详情对话框 -->
    <BatchDetail
      v-model:visible="detailVisible"
      :record="currentRecord"
    />
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { 
  getVerifyBatchList, 
  importAndReconcile,
  exportReconciliationResult,
  saveReconciliationResult,
  exportRecords,
  getVerifyBatch
} from '@/api/order/reconciliation';
import type { 
  OrderVerifyBatchQuery,
  OrderVerifyBatch
} from '@/api/order/reconciliation/types';
import ReconciliationResult from './components/reconciliation-result.vue';
import BatchDetail from './components/verify-batch-detail.vue';
import UploadDialog from './components/upload-dialog.vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 加载状态
const { loading, setLoading } = useLoading();

// 对话框状态
const resultVisible = ref(false);
const uploadVisible = ref(false);
const detailVisible = ref(false);
const currentRecord = ref<OrderVerifyBatch | null>(null);

// 对账结果
const reconciliationResult = ref<OrderVerifyBatch[]>([]);
const reconciliationStatistics = ref<Record<string, any>>({});

// 日期范围
const timeRange = ref<string[]>([]);

// 表格列定义
const columns = computed(() => [
  {
    title: '批次号',
    dataIndex: 'batchNo',
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '平台ID',
    dataIndex: 'platformId',
    width: 120,
  },
  {
    title: '总笔数',
    dataIndex: 'totalCount',
    width: 100,
  },
  {
    title: '成功笔数',
    dataIndex: 'successCount',
    width: 100,
    slotName: 'successCount',
  },
  {
    title: '失败笔数',
    dataIndex: 'failCount',
    width: 100,
    slotName: 'failCount',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    slotName: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'operations',
    slotName: 'operations',
    width: 250,
    fixed: 'right',
  },
]);

// 表格数据
const renderData = ref<OrderVerifyBatch[]>([]);

// 分页参数
const basePagination = {
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
};
const pagination = reactive({
  ...basePagination,
});

// 搜索表单
const searchForm = reactive<OrderVerifyBatchQuery>({
  current: 1,
  size: 10,
  batchNo: '',
  platformId: undefined,
  status: undefined,
  startTime: undefined,
  endTime: undefined,
});

// 搜索
function search() {
  fetchData();
}

// 重置搜索条件
function reset() {
  searchForm.batchNo = '';
  searchForm.platformId = undefined;
  searchForm.status = undefined;
  timeRange.value = [];
  fetchData();
}

// 分页变化
function onPageChange(current: number) {
  pagination.current = current;
  fetchData();
}

// 每页条数变化
function onPageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.current = 1;
  fetchData();
}

// 查看详情
async function viewDetail(record: OrderVerifyBatch) {
  try {
    setLoading(true);
    const res = await getVerifyBatch(record.batchNo);
    currentRecord.value = res.data;
    detailVisible.value = true;
  } catch (error) {
    console.error('获取核对批次详情失败:', error);
    Message.error('获取核对批次详情失败');
  } finally {
    setLoading(false);
  }
}

// 查看对账记录
function viewRecords(record: OrderVerifyBatch) {
  // 跳转到对账记录列表页面，并传递批次号参数
  router.push({
    name: 'ReconciliationRecords',
    query: { batchNo: record.batchNo }
  });
}

// 导出批次记录
async function exportBatchRecords(record: OrderVerifyBatch) {
  try {
    setLoading(true);
    await exportRecords({
      batchNo: record.batchNo
    });
    Message.success('导出成功');
  } catch (error) {
    console.error('导出对账记录失败:', error);
    Message.error('导出失败');
  } finally {
    setLoading(false);
  }
}

// 处理导入
const handleImport = () => {
  uploadVisible.value = true;
};

// 处理上传成功
const handleUploadSuccess = () => {
  uploadVisible.value = false;
  fetchData();
};

// 导出数据
async function exportData() {
  try {
    setLoading(true);
    const params = { ...searchForm };
    if (timeRange.value && timeRange.value.length === 2) {
      params.startTime = timeRange.value[0];
      params.endTime = timeRange.value[1];
    }
    await exportRecords(params);
    Message.success('导出成功');
  } catch (error) {
    console.error('导出对账记录失败:', error);
    Message.error('导出失败');
  } finally {
    setLoading(false);
  }
}

// 保存对账结果
async function handleSaveResult(batchName: string) {
  try {
    setLoading(true);
    const batchNo = await saveReconciliationResult(batchName, reconciliationResult.value);
    Message.success('保存成功');
    resultVisible.value = false;
    fetchData();
  } catch (error) {
    console.error('保存对账结果失败:', error);
    Message.error('保存失败');
  } finally {
    setLoading(false);
  }
}

// 获取对账批次数据
async function fetchData() {
  setLoading(true);
  try {
    const params = { ...searchForm };
    params.current = pagination.current;
    params.size = pagination.pageSize;
    
    if (timeRange.value && timeRange.value.length === 2) {
      params.startTime = timeRange.value[0];
      params.endTime = timeRange.value[1];
    }
    
    const res = await getVerifyBatchList(params);
    renderData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    console.error('获取核对批次列表失败:', error);
    Message.error('获取核对批次列表失败');
  } finally {
    setLoading(false);
  }
}

onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="less">
.container {
  padding: 0 20px 20px 20px;
}

.general-card {
  :deep(.arco-card-header) {
    padding: 20px;
  }
  :deep(.arco-card-body) {
    padding: 0 20px 20px 20px;
  }
}
</style> 